<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BUIAppAdmin
 *
 * @author I062261
 */
class BUIAppAdmin extends BUIThemedControl {

//put your code here

    public function onRun($data = NULL) {
        parent::onRun($data);
    }

    public function runAppAdmin($data = NULL) {
        $screen = Blyn::app()->getUIManager()->getCurrentScreen();
        $sender = Blyn::app()->getUIManager()->getSenderControl();
        //$updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $page = new BUIThemedControl('page');
        $screen->addChildControl($page);

        $viewData = array();
        $operationRoleList = $this->getOperationRoleList();
        $viewData['operationRoleList'] = $operationRoleList;

        if ($sender instanceof BUIOperation) {
            $page->addRenderView('operationRoleList', 'operation_role_list', $viewData);
        }
    }

    public function onShowOperationRoleList($data = NULL) {
        $sender = Blyn::app()->getUIManager()->getSenderControl();
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();

        $viewData = array();
        $operationRoleList = $this->getOperationRoleList();
        $viewData['operationRoleList'] = $operationRoleList;

        //if ($sender instanceof BUIOperation) {
        $updateControl->addRenderView('operationRoleList', 'operation_role_list', $viewData);
        //}
    }

    public function onShowAddOperationRole($data = NULL) {
        $activeLink = Blyn::app()->getUIManager()->getActiveLink();
        $operationRoleId = $activeLink->getLinkVariable('operationRoleId');

        $model = new BDynamicFormModel();
        $roleIdField = 'media_roleId_add_operation_role';
        $operationIdField = 'media_operationId_add_operation_role';
        $permitIdField = 'media_permitId_add_operation_role';
        $model->addField($roleIdField);
        $model->addField($operationIdField);
        $model->addField($permitIdField);

        if (is_numeric($operationRoleId) && $operationRoleId > 0) {
            $dbObj = BMResourcePermitRole::model()->findByPk($operationRoleId);
            $roleId = $dbObj->role_id;
            $operationid = $dbObj->resource_id;
            $permitId = $dbObj->permit_id;

            $model->$roleIdField = $roleId;
            $model->$operationIdField = $operationid;
            $model->$permitIdField = $permitId;
        }

        //prepare view data
        $viewData = array();
        $viewData['model'] = $model;
        $viewData['roleIdField'] = $roleIdField;
        $viewData['permitIdField'] = $permitIdField;
        $viewData['operationIdField'] = $operationIdField;

        //operationData
        $operationData = array();
        $operations = Blyn::app()->getActiveApp()->getOperations();
        foreach ($operations as $id => $operation) {
            $operationData[$id] = $operation->getName();
        }
        $viewData['operationData'] = $operationData;

        //permitData
        $permitData = array();
        $permits = BPermit::getRoot()->getChildrenAsLeaf();
        foreach ($permits as $id => $permit) {
            $permitData[$id] = $permit->getName();
        }
        $viewData['permitData'] = $permitData;

        //roleData
        $roleControl = new BUIRole();
        $roleData = $roleControl->getAllAppRoleData();
        $viewData['roleData'] = $roleData;

        $operationRoleData = array();
        foreach ($operationData as $opId => $opName) {
            foreach ($roleData as $rId => $roleName) {
                foreach ($permitData as $pId => $permitName) {
                    $id = $opId . '_' . $rId . '_' . $pId;
                    $operationRoleData[$id] = array(
                        'operationName' => $opName,
                        'roleName' => $roleName,
                        'permitName' => $permitName
                    );
                }
            }
        }
        $viewData['operationRoleData'] = $operationRoleData;

        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $updateControl->addRenderView('addOperationRole', 'operation_role_add', $viewData);
    }

    public function onAddOperationRole($data = NULL) {
        $activeLink = Blyn::app()->getUIManager()->getActiveLink();
        $operationRoleId = $activeLink->getLinkVariable('operationRoleId');

        $postManager = new BPostManager();
        $postData = $postManager->parsedModelData();
        $mediaList = $postManager->populateMediaListFromPostData($postData, 'add_operation_role');

        $roleId = $mediaList['roleId']->content;
        $opId = $mediaList['operationId']->content;
        $permitId = $mediaList['permitId']->content;

        if (is_numeric($operationRoleId) && $operationRoleId > 0) {
            $dbObj = BMResourcePermitRole::model()->findByPk($operationRoleId);
        } else {
            $dbObj = new BMResourcePermitRole();
        }

        $dbObj->resource_class = 'BOperation';
        $dbObj->resource_id = $opId;
        $dbObj->role_id = $roleId;
        $dbObj->permit_id = $permitId;

        $result = $dbObj->save();

        $viewData = array();
        $actionResult = NULL;
        if ($result == FALSE) {
            $actionResult = 'fail to save!';
        }

        if ($actionResult == NULL) {
            $this->onShowOperationRoleList();
        } else {
            $viewData['actionResult'] = $actionResult;
            $this->onShowAddOperationRole($viewData);
        }
    }

    public function onDeleteOperationRole($data = NULL) {
        $activeLink = Blyn::app()->getUIManager()->getActiveLink();
        $operationRoleId = $activeLink->getLinkVariable('operationRoleId');

        if (is_numeric($operationRoleId) && $operationRoleId > 0) {
            BMResourcePermitRole::model()->deleteByPk($operationRoleId);
        }
        $this->onShowOperationRoleList();
    }

    public function onDeleteEventShare($data = NULL) {
        $activeLink = Blyn::app()->getUIManager()->getActiveLink();
        $eventShareId = $activeLink->getLinkVariable('eventShareId');
        $eventShareTable = new BASheet('eventShare');

        if (is_numeric($eventShareId) && $eventShareId > 0) {
            $eventShareTable->deleteList($eventShareId);
        }
        $this->onShowEventShareList($data);
    }

    public function onDeleteEventShareAccess($data = NULL) {
        $activeLink = Blyn::app()->getUIManager()->getActiveLink();
        $eventShareAccessId = $activeLink->getLinkVariable('eventShareAccessId');
        $eventShareAccessTable = new BASheet('eventShareAccess');

        if (is_numeric($eventShareAccessId) && $eventShareAccessId > 0) {
            $eventShareAccessTable->deleteList($eventShareAccessId);
        }
        $this->onShowEventShareAccessList($data);
    }

    /**
     * this function will list operation-role couple
     * 
     * @param type $data
     * @return type
     */
    protected function getOperationRoleList($data = NULL) {

        $app = Blyn::app()->getActiveApp();
        $operations = $app->getOperations();
        $roles = $app->getRoles();

        $list = array();

        foreach ($operations as $opId => $operation) {
            $list+=$this->populateOperationRoleList($opId, NULL, array('spaceId' => Blyn::app()->getActiveSpace()->getId()));
        }

        $list += $this->getRelatedSpaceOperationRoleList();

        return $list;
    }

    /**
     * this function use to get operation-role list from related space
     * @param type $data
     */
    protected function getRelatedSpaceOperationRoleList($data = NULL) {

        $spaceConn = new BUISpaceConn();
        $spaceRelationshipView = $spaceConn->getSpaceRelationshipList();
        $list = array();

        foreach ($spaceRelationshipView as $srList) {
            $spaceId = $srList->getItem('spaceId')->getValue();
            $space = new BSpace($spaceId);
            $apps = $space->getApps();
            foreach ($apps as $app) {
                if ($app instanceof BApp) {
                    $operations = $app->getOperations();
                    foreach ($operations as $id => $operation) {
                        $list += $this->populateOperationRoleList($id, NULL, array('spaceId' => $spaceId));
                    }
                }
            }
        }

        return $list;
    }

    protected function populateOperationRoleList($operation = null, $role = NULL, $data = array()) {

        $operationId = NULL;
        $roleId = NULL;

        if ($operation != NULL) {
            if (is_numeric($operation)) {
                $operationId = $operation;
                $operation = new BOperation($operationId);
            } elseif ($operation instanceof BOperation) {
                $operationId = $operation->getId();
            }
        }

        if ($role != NULL) {
            if (is_numeric($role)) {
                $roleId = $role;
                $role = new BRole($roleId);
            } elseif ($role instanceof BRole) {
                $roleId = $role->getId();
            }
        }

        $condition = array();
        if (is_numeric($operationId) && $operationId > 0) {
            $condition['resource_id'] = $operationId;
            $condition['resource_class'] = 'BOperation';
        }
        if (is_numeric($roleId) && $roleId > 0) {
            $condition['role_id'] = $roleId;
        }
        $modelList = BMResourcePermitRole::model()->findAllByAttributes($condition);
        $orlist = array();
        foreach ($modelList as $model) {
            $roleId = $model->role_id;
            $role = new BRole($roleId);
            $permitId = $model->permit_id;
            $list = array();
            $list['operationRoleId'] = $model->_id;
            $list['operationId'] = $operationId;
            $list['operationName'] = $operation->getName();
            $list['roleId'] = $roleId;
            $list['roleName'] = $role->getName();
            $list['roleFullName'] = $role->getFullName();
            $permit = new BPermit($permitId);
            $list['permitId'] = $permitId;
            $list['permitName'] = $permit->name;
            if (is_array($data) && $data != NULL) {
                $list+= $data;
            }
            $orlist[$model->_id] = $list;
        }
        return $orlist;
    }

    /**
     * this function will return shared event list
     * @param type $data
     */
    public function onShowEventShareList($data = NULL) {

        $eventShareTable = new BASheet('eventShare');

        $space = Blyn::app()->getActiveSpace();
        $app = Blyn::app()->getActiveApp();

        $itemData = array();
        $itemData['spaceId'] = $space->getId();
        $itemData['appId'] = $app->getId();

        $sharedView = $eventShareTable->getView(array('itemData' => $itemData));
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();

        $updateControl->addRenderView('showEventShareList', 'event_share_list', array('eventShareView' => $sharedView));
        //return $sharedView;
    }

    public function onShowEventShareAccessList($data = NULL) {
        $eventShareAccessTable = new BASheet('eventShareAccess');

        $space = Blyn::app()->getActiveSpace();
        $app = Blyn::app()->getActiveApp();

        $itemData = array();
        $itemData['spaceId'] = $space->getId();
        $itemData['appId'] = $app->getId();

        $accessView = $eventShareAccessTable->getView(array('itemData' => $itemData));
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();

        $updateControl->addRenderView('showEventShareAccessList', 'event_share_access_list', array('eventShareAccessView' => $accessView));
        //return $sharedView;
    }

    public function onShowAddEventShareAccess($data = NULL) {
        $activeLink = Blyn::app()->getUIManager()->getActiveLink();
        $eventShareAccessId = $activeLink->getLinkVariable('eventShareAccessId');
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();

        $eventShareAccessTable = new BASheet('eventShareAccess');
        $eventShareAccess = NULL;
        if (is_numeric($eventShareAccessId) && $eventShareAccessId > 0) {
            $eventShareAccess = $eventShareAccessTable->getListById($eventShareAccessId);
        }

        $model = new BDynamicFormModel();
        $eventIdField = 'media_eventId_add_event_share_access';
        $operationIdField = 'media_operationId_add_event_share_access';
        $allowSpaceField = 'media_allowSpace_add_event_share_access';

        $model->addField($eventIdField);
        $model->addField($operationIdField);
        $model->addField($allowSpaceField);

        if ($eventShareAccess != NULL) {
            $model->$eventIdField = $eventShareAccess->getItem('eventId')->getValue();
            $model->$operationIdField = $eventShareAccess->getItem('operationId')->getValue();
            $model->$allowSpaceField = $eventShareAccess->getItem('allowSpace')->getValue();
        }

        //operation list
        $operations = Blyn::app()->getActiveApp()->getOperations();
        $operationData = array();
        foreach ($operations as $id => $operation) {
            $operationData[$id] = $operation->getName();
        }

        //eventList
        $eventCooker = new BAEventCooker();
        $eventView = $eventCooker->getEventView();
        $eventData = array();

        foreach ($eventView as $id => $list) {
            $eventData[$id] = $list->getItem('name')->getValue();
        }

        //spaceRelationshipData
        $spaceConnControl = new BUISpaceConn();
        $spaceRelationshipData = $spaceConnControl->getRelationshipData();

        $updateControl->addRenderView('addEventShareAccess', 'event_share_access_add', array(
            'model' => $model,
            'eventIdField' => $eventIdField,
            'operationIdField' => $operationIdField,
            'allowSpaceField' => $allowSpaceField,
            'operationData' => $operationData,
            'eventData' => $eventData,
            'spaceRelationshipData' => $spaceRelationshipData,
            'eventShareAccessId' => $eventShareAccessId
        ));
    }

    public function onAddEventShareAccess($data = NULL) {
        $activeLink = Blyn::app()->getUIManager()->getActiveLink();
        //$updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $postManager = new BPostManager();
        $postData = $postManager->parsedModelData();

        $mediaList = $postManager->populateMediaListFromPostData($postData, 'add_event_share_access');

        //$eventId = $mediaList['eventId'];
        $operationId = $mediaList['operationId']->content;
        $allowSpace = $mediaList['allowSpace']->content;

        //$event = NULL;
        $operation = NULL;
        //if (is_numeric($eventId) && $eventId > 0) {
        //$eventTable = new BAEventSheet();
        //$event = $eventTable->getListById($eventId);
        //}

        if (is_numeric($operationId) && $operationId > 0) {
            $operation = new BOperation($operationId);
        }

        if ($operation != NULL) {
            $eventShareAccessTable = new BASheet('eventShareAccess');
            $itemData = array();
            //$itemData['eventId'] = $eventId;
            //$itemData['eventName'] = $event->getItem('name')->getValue();
            $itemData['operationId'] = $operationId;
            $itemData['operationName'] = $operation->getName();
            $itemData['spaceId'] = Blyn::app()->getActiveSpace()->getId();
            $itemData['appId'] = Blyn::app()->getActiveApp()->getId();
            $itemData['allowSpace'] = $allowSpace;
            $eventShareAccessTable->addList($itemData);
        }

        $this->onShowEventShareAccessList($data);

        //$updateControl->addRenderView('event_share_access_list');
    }

    public function onShowAddEventShare($data = NULL) {
        $activeLink = Blyn::app()->getUIManager()->getActiveLink();
        $eventShareId = $activeLink->getLinkVariable('eventShareId');
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();

        $eventShareTable = new BASheet('eventShare');
        $eventShare = NULL;
        if (is_numeric($eventShareId) && $eventShareId > 0) {
            $eventShare = $eventShareTable->getListById($eventShareId);
        }

        $model = new BDynamicFormModel();
        $eventIdField = 'media_eventId_add_event_share';
        $operationIdField = 'media_operationId_add_event_share';
        $shareToSpaceField = 'media_shareToSpace_add_event_share';

        $model->addField($eventIdField);
        $model->addField($operationIdField);
        $model->addField($shareToSpaceField);

        if ($eventShare != NULL) {
            $model->$eventIdField = $eventShare->getItem('eventId')->getValue();
            $model->$operationIdField = $eventShare->getItem('operationId')->getValue();
            $model->$shareToSpaceField = $eventShare->getItem('shareToSpace')->getValue();
        }

        //operation list
        $operations = Blyn::app()->getActiveApp()->getOperations();
        $operationData = array();
        foreach ($operations as $id => $operation) {
            $operationData[$id] = $operation->getName();
        }

        //eventList
        $eventCooker = new BAEventCooker();
        $eventView = $eventCooker->getEventView();
        $eventData = array();

        foreach ($eventView as $id => $list) {
            $eventData[$id] = $list->getItem('name')->getValue();
        }

        //spaceRelationshipData
        $spaceConnControl = new BUISpaceConn();
        $spaceRelationshipData = $spaceConnControl->getRelationshipData();

        $updateControl->addRenderView('addEventShare', 'event_share_add', array(
            'model' => $model,
            'eventIdField' => $eventIdField,
            'operationIdField' => $operationIdField,
            'shareToSpaceField' => $shareToSpaceField,
            'operationData' => $operationData,
            'eventData' => $eventData,
            'spaceRelationshipData' => $spaceRelationshipData,
            'eventShareId' => $eventShareId
        ));
    }

    public function onAddEventShare($data = NULL) {
        //$activeLink = Blyn::app()->getUIManager()->getActiveLink();
        //$eventId = $activeLink->getLinkVariable('eventId');
        //$operationId = $activeLink->getLinkVariable('operationId');
        //$shareToSpace = $activeLink->getLinkVariable('shareToSpace');
        //$updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $postManager = new BPostManager();
        $postData = $postManager->parsedModelData();
        $mediaList = $postManager->populateMediaListFromPostData($postData, 'add_event_share');
        $eventId = $mediaList['eventId']->content;
        $operationId = $mediaList['operationId']->content;
        $shareToSpace = $mediaList['shareToSpace']->content;

        $event = NULL;
        $operation = NULL;
        if (is_numeric($eventId) && $eventId > 0) {
            $eventTable = new BAEventSheet();
            $event = $eventTable->getListById($eventId);
        }

        if (is_numeric($operationId) && $operationId > 0) {
            $operation = new BOperation($operationId);
        }

        if ($event != NULL && $operation != NULL) {
            $eventShareTable = new BASheet('eventShare');
            $itemData = array();
            $itemData['eventId'] = $eventId;
            $itemData['eventName'] = $event->getItem('name')->getValue();
            $itemData['operationId'] = $operationId;
            $itemData['operationName'] = $operation->getName();
            $itemData['spaceId'] = Blyn::app()->getActiveSpace()->getId();
            $itemData['appId'] = Blyn::app()->getActiveApp()->getId();
            $itemData['shareToSpace'] = $shareToSpace;
            $list = $eventShareTable->getList(array('itemData' => $itemData));
            if ($list == NULL)
                $eventShareTable->addList($itemData);
        }

        $this->onShowEventShareList($data);
        //$updateControl->addRenderView('event_share_list');
    }

    /**
     * this function use to find shared event list for current operation
     * in event list, call this function to get event list from shared space
     * 
     * @param type $data
     */
    public function getSharedEventList($data = NULL) {
        $operation = Blyn::app()->getActiveOperation();
        $eventList = array();

        $eventShareAccess = new BASheet('eventShareAccess');

        $view = $eventShareAccess->getView(array('itemData' => array(
                'operationId' => $operation->getId()
        )));

        foreach ($view as $key => $list) {
            $allowSpace = $list->getItem('allowSpace')->getValue();
            if ($allowSpace == BUISpaceConn::Relationship_Father_Space) {
                $eventList+= $this->getFatherSpaceEventList();
            }
            if ($allowSpace == BUISpaceConn::Relationship_Son_Space) {
                $eventList+= $this->getSonSpaceEventList();
            }
        }
        return $eventList;
    }

    public function getFatherSpaceEventList($data = NULL) {
        $eventList = array();

        $spaceConn = new BUISpaceConn();
        $operation = Blyn::app()->getActiveOperation();
        $operationName = $operation->getName();
        $itemContext = array($operationName . 'Home' => $operationName);

        $fatherSpaceList = $spaceConn->getSpaceRelationshipList(BUISpaceConn::Relationship_Father_Space);

        foreach ($fatherSpaceList as $key => $list) {
            $spaceId = $list->getItem('spaceId')->getValue();
            $space = new BSpace($spaceId);
            $eventTable = new BAEventSheet($space);

            ///*
            $eventShareTable = new BASheet('eventShare', $space);

            $shareList = $eventShareTable->getValueList('eventId', array('itemData' => array(
                    'spaceId' => $space->getId(),
                    'shareToSpace' => BUISpaceConn::Relationship_Son_Space,
                    'operationName' => $operationName
            )));

            if (is_array($shareList)) {
                $eventIdList = array();
                foreach ($shareList as $key => $value) {
                    array_push($eventIdList, $key);
                }
                //$itemContext['eventId'] = $eventIdList;
            }

            //*/

            $eventList += $eventTable->getView(array('itemData' => $itemContext));
            $finalList = array();
            foreach ($eventList as $key => $value) {
                if (in_array($key, $eventIdList)) {
                    $finalList[$key] = $value;
                }
            }
            return $finalList;
        }

        return array();
    }

    public function getSonSpaceEventList($data = NULL) {
        
    }

    /**
     * this function use to add allow access shared event
     * @param type $data
     */
    public function addEventShareAccess($operationId, $eventId, $allowSpace, $data = NULL) {

        $eventShareAccess = new BASheet('eventShareAccess');

        $eventShareAccess->addList(array(
            'eventId' => $eventId,
            'operationId' => $operationId,
            'allowSpace' => $allowSpace
        ));
    }

}
